﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;

namespace MPMovieCatalogServer.Server
{
    public class HttpServer
    {
        protected HttpListener listener;
        protected bool isStarted = false;

        public HttpServer()
        {

        }

        public void Start(string UrlBase)
        {
            if (isStarted) return;

            if (listener == null)
            {
                listener = new HttpListener();
            }

            listener.Prefixes.Add(UrlBase);

            isStarted = true;
            listener.Start();
            listener.BeginGetContext(new AsyncCallback(WebRequestCallback), listener);
        }

        public void Stop()
        {
            if (listener != null)
            {
                listener.Close();
                listener = null;
                isStarted = false;
            }
        }

        protected void WebRequestCallback(IAsyncResult result)
        {
            if (listener == null) return;

            HttpListenerContext context = listener.EndGetContext(result);

            listener.BeginGetContext(new AsyncCallback(WebRequestCallback), listener);

            new Thread(new Worker(context).ProcessRequest).Start();
        }
    }
}
